<?php
namespace app\channel\controller\sys_admin;
use think\Db;

use app\AdminController;
use app\channel\model\ChannelGoodsModel;
use app\channel\model\ChannelGoodsPricesModel;
use app\channel\model\ProxyLevelModel;

use app\shop\model\GoodsModel;
use app\channel\model\GoodsUnitModel;


/**
 * 代理商品管理
 * Class Index
 * @package app\store\controller
 */
class Goods extends AdminController
{
	/*------------------------------------------------------ */
	//-- 优先执行
	/*------------------------------------------------------ */
	public function initialize(){
        parent::initialize();
        $this->Model = new ChannelGoodsModel();
    }
	/*------------------------------------------------------ */
	//-- 主页
	/*------------------------------------------------------ */
    public function index(){
        $this->getList(true);
		return $this->fetch();
	}
    /*------------------------------------------------------ */
    //-- 获取列表
    //-- $runData boolean 是否返回模板
    /*------------------------------------------------------ */
    public function getList($runData = false)
    {
        $search['status'] = input('status', -1, 'intval');
        if ($search['status'] == 1) {
            $where[] = ['cg.isputaway', '=', 1];
        } elseif ($search['status'] == 2) {
            $where[] = ['cg.isputaway', '=', 0];
        }

        $search['keyword'] = input('keyword', '', 'trim');
        if (empty($search['keyword']) == false) {
            $where['and'][] = "( sg.goods_name like '%" . $search['keyword'] . "%')  OR ( sg.goods_sn like '%" . $search['keyword'] . "%')";
        }
        $GoodsModel = new GoodsModel();
        $classList = $GoodsModel->getClassList();
        $search['cid'] = input('cat_id', 0, 'intval');
        if ($search['cid'] > 0) {
            $where[] = ['sg.cid', 'in', $classList[$search['cid']]['children']];
        }
        $viewObj = $this->Model->alias('cg')->join("shop_goods sg", 'cg.goods_id=sg.goods_id', 'left')->where($where)->field('cg.id,cg.goods_id,cg.isputaway,cg.unit,sg.goods_name')->order('cg.id DESC');
        $data = $this->getPageList($this->Model, $viewObj);
        $this->assign("data", $data);
        $this->assign("search", $search);
        $this->assign("classListOpt", arrToSel($classList, $search['cid']));
        $this->assign('goodsUnit',(new GoodsUnitModel)->getRows());

        if ($runData == false) {
            $data['content'] = $this->fetch('list')->getContent();
            unset($data['list']);
            return $this->success('', '', $data);
        }
        return true;
    }
    /*------------------------------------------------------ */
    //-- 选择商品
    /*------------------------------------------------------ */
    public function selectGoods(){
        if ($this->request->isPost() == true){
            $goods_id = input('goods_id',0,'intval');
            $count = $this->Model->where('goods_id',$goods_id)->count();
            if ($count > 0){
                return $this->error('代理商品已存在，不能重复添加.');
            }
            return $this->success();
        }
        return $this->fetch();
    }
    /*------------------------------------------------------ */
    //-- 详细页调用
    /*------------------------------------------------------ */
    public function asInfo($data) {
        $prices = [];
        if (empty($data['id']) == true){
            $sel_goods_id = input('sel_goods_id',0,'intval');
            if ($sel_goods_id < 1){
                return $this->error('请选择商品.');
            }
            $count = $this->Model->where('goods_id',$sel_goods_id)->count();
            if ($count > 0){
                return $this->error('代理商品已存在，不能重复添加.');
            }
        }else{
            $sel_goods_id = $data['goods_id'];
            $data['convert_unit'] = json_decode($data['convert_unit'],true);
            $prices = (new ChannelGoodsPricesModel)->where('goods_id',$sel_goods_id)->select()->toArray();
        }
        $GoodsModel = new GoodsModel();
        $goodsInfo = $GoodsModel->info($sel_goods_id);
        if (empty($goodsInfo)){
            return $this->error('没有找到相关商品信息.');
        }
        $this->assign('proxyLevel',(new ProxyLevelModel)->getList(true));
        print_r();
        $this->assign('goodsInfo',$goodsInfo);
        $this->assign('prices',$prices);
        $ClassList = $GoodsModel->getClassList();
        $this->assign('className',$ClassList[$goodsInfo['cid']]['name']);
        $this->assign('goodsUnit',(new GoodsUnitModel)->getRows());
        return $data;
    }
    /*------------------------------------------------------ */
    //-- 验证商品数据
    /*------------------------------------------------------ */
    private function checkData($data)
    {
        $goodsInfo = (new GoodsModel)->info($data['goods_id']);

        if (empty($goodsInfo)){
            return $this->error('没有找到关联商品信息.');
        }
        //自动上下架处理
        if ($data['isputaway'] == 2) {
            if (empty($data['added_time']) || empty($data['shelf_time'])) return $this->error('操作失败:请选择上下架的时间.');
            if (!checkDateIsValid($data['added_time'])) return $this->error('操作失败:上下架的开始时间格式不合法.');
            if (!checkDateIsValid($data['shelf_time'])) return $this->error('操作失败:上下架的结束时间格式不合法.');
            $data['added_time'] = strtotime($data['added_time']);
            $data['shelf_time'] = strtotime($data['shelf_time']);
            if ($data['added_time'] >= $data['shelf_time']) return $this->error('操作失败:下架时间必须大于上架时间.');
        }else{
            $data['added_time'] = strtotime($data['added_time']);
            $data['shelf_time'] = strtotime($data['shelf_time']);
            if ($data['shelf_time'] < time()){//如何下架时间小于当前时间，直接设为零
                $data['shelf_time'] = 0;
            }
        }

        if (empty($data['unit'])){
            return $this->error('请选择默认计量单位.');
        }
        $data['convert_unit'] = [];
        $convert_unit = 0;
        if (empty($data['convert_unit_id']) == false){

            foreach ($data['convert_unit_id'] as $key=>$cuid){
                if (empty($data['convert_unit_val'][$key])){
                    return $this->error('请填写换算单位数量.');
                }
                if ($convert_unit > $data['convert_unit_val'][$key]){
                    return $this->error('请按从小到大顺序添加换算单位数量.');
                }
                $convert_unit = $data['convert_unit_val'][$key];
                $data['convert_unit'][$cuid] = $convert_unit;
            }
        }

        unset($data['convert_unit_id'],$data['convert_unit_val']);
        $data['convert_unit'] = json_encode($data['convert_unit']);
        if (empty($data['price_type'])){
            $data['price_type'] = 0;
        }
        $proxyLevel = (new ProxyLevelModel)->getList(true);
        $prices = $data['price'];
        $pl_prices = [];
        if ($data['price_type'] == 0){//统一定价判断
            $now_price = 0;
            foreach ($proxyLevel as $pl){
                if (empty($prices[$pl['proxy_id']])){
                    return $this->error('请填写【'.$pl['proxy_name'].'】的层级定价.');
                }
                if ($now_price > $prices[$pl['proxy_id']]){
                    return $this->error('【'.$pl['proxy_name'].'】的层级定价，不能低于上级定价.');
                }
                $now_price = $prices[$pl['proxy_id']];
                $arr = [];
                $arr['price_type'] = $data['price_type'];
                $arr['proxy_id'] = $pl['proxy_id'];
                $arr['goods_id'] = $data['goods_id'];
                $arr['price'] = $now_price;
                $arr['sku_id'] = 0;
                $pl_prices[] = $arr;
            }
        }else{
            if ($goodsInfo['is_spec'] == 0){
                return $this->error('发生错误，只有多规格商品才能设置独立价.');
            }
            foreach ($proxyLevel as $pl){
                $now_price = 0;
                foreach ($goodsInfo['sub_goods'] as $sg){
                    if (empty($prices[$pl['proxy_id']][$sg['sku_id']])){
                        return $this->error('请填写【'.$pl['proxy_name'].'：'.$sg['sku_name'].'】的层级定价.');
                    }
                    if ($now_price > $prices[$pl['proxy_id']][$sg['sku_id']]){
                        return $this->error('【'.$pl['proxy_name'].'】的层级定价，不能低于上级定价.');
                    }
                    $now_price = $prices[$pl['proxy_id']][$sg['sku_id']];
                    $arr = [];
                    $arr['price_type'] = $data['price_type'];
                    $arr['goods_id'] = $data['goods_id'];
                    $arr['proxy_id'] = $pl['proxy_id'];
                    $arr['price'] = $now_price;
                    $arr['sku_id'] = $sg['sku_id'];
                    $pl_prices[] = $arr;
                }
            }
        }
        unset($data['price']);
        $this->pl_prices = $pl_prices;
        return $data;
    }
    /*------------------------------------------------------ */
    //-- 添加前处理
    /*------------------------------------------------------ */
    public function beforeAdd($data) {
        $data = $this->checkData($data);
        $data['add_time'] = time();
        Db::startTrans();//开启事务
        return $data;
    }
    /*------------------------------------------------------ */
    //-- 添加后调用
    /*------------------------------------------------------ */
    public function afterAdd($data){
        $ChannelGoodsPricesModel = new ChannelGoodsPricesModel();
        foreach ($this->pl_prices as $price){
            $res = $ChannelGoodsPricesModel::create($price);
            if ($res < 1) {
                Db::rollback();// 回滚事务
                return $this->error('操作失败:写入层级定价失败，请重试.');
            }
        }
        Db::commit();// 提交事务
        if ($data['price_type'] == 0){
            $log = ',价格规则：统一出货价';
        }else{
            $log = ',价格规则：独立出货价';
        }
        $this->Model->cleanMemcache($data['goods_id']);
        $this->_Log($data['id'],'添加代理商品:'.$data['goods_id'].$log);
        return $this->success('添加成功.',url('index'));
    }
    /*------------------------------------------------------ */
    //-- 修改前处理
    /*------------------------------------------------------ */
    public function beforeEdit($data){
        $data = $this->checkData($data);
        $data['update_time'] = time();
        Db::startTrans();//开启事务
        return $data;
    }
    /*------------------------------------------------------ */
    //-- 修改后调用
    /*------------------------------------------------------ */
    public function afterEdit($data){
        $ChannelGoodsPricesModel = new ChannelGoodsPricesModel();
        foreach ($this->pl_prices as $price){
            $where = [];
            $where['price_type'] = $price['price_type'];
            $where['proxy_id'] = $price['proxy_id'];
            $where['goods_id'] = $price['goods_id'];
            $where['sku_id'] = $price['sku_id'];
            $id = $ChannelGoodsPricesModel->where($where)->value('id');
            if ($id > 0){
                $price['update_time'] = $data['update_time'];
                $res = $ChannelGoodsPricesModel->where('id',$id)->update($price);
            }else{
                $price['update_time'] = $data['update_time'];
                $res = $ChannelGoodsPricesModel::create($price);
            }
            if ($res < 1) {
                Db::rollback();// 回滚事务
                return $this->error('操作失败:写入层级定价失败，请重试.');
            }
        }
        Db::commit();// 提交事务
        if ($data['price_type'] == 0){
            $log = ',价格规则：统一出货价';
        }else{
            $log = ',价格规则：独立出货价';
        }
        $this->Model->cleanMemcache($data['goods_id']);
        $this->_Log($data['id'],'修改代理商品:'.$data['goods_id'].$log);
        return $this->success('修改成功.','reload');
    }

}
